package forum.view.listeners.user;

import java.util.Date;
import java.util.GregorianCalendar;

import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

import sun.util.calendar.JulianCalendar;


import forum.business.entities.UserBO;
import forum.business.facades.UserFacade;
import forum.util.exceptions.AdException;
import forum.view.managedbeans.UserDataBean;

public class CreateUserListener implements ActionListener {

	public void processAction(ActionEvent e) throws AbortProcessingException {
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		UserDataBean userData = (UserDataBean) getValueBinding("#{userDataBean}").getValue(facesContext);
		UserBO userBO = wrapUserData(userData);
		
		UserFacade userFacade = new UserFacade();
		try {
			userFacade.createUser(userBO);
		} catch (AdException ex) {
			System.err.println(ex.getMessage());
		}
		
	}

	private ValueBinding getValueBinding(String valueRef) {
		ApplicationFactory factory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
		Application application = factory.getApplication();
		return application.createValueBinding(valueRef);
	}
	
	private UserBO wrapUserData(UserDataBean userData){
		UserBO userBO = new UserBO();
		userBO.setLogin(userData.getLogin());
		userBO.setStatus(userData.getStatus());
		userBO.setPassword(userData.getPassword());
		userBO.setEmail(userData.getEmail());
		userBO.setCity(userData.getCity());
		userBO.setCountry(userData.getCountry());
		userBO.setBirthDate(getBirthDate(userData));
		userBO.setIsFemale(userData.getIsFemale() == 0 ? true : false);
		userBO.setPostsCounter(0);
		userBO.setJoinDate(new Date());
		userBO.setName(userData.getName());
		userBO.setSurname(userData.getSurname());
		return userBO;
	}
	
	private Date getBirthDate(UserDataBean userData){
		int day = userData.getDay()+1;
		int month = userData.getMonth()-1;
		int year = userData.getYear();
		GregorianCalendar gregorian = new GregorianCalendar(year, month, day);
		return gregorian.getTime();
	}
	
	
}
